package cn.cj.erp.common.security.security.handle;

import cn.cj.erp.common.enums.StatusEnum;
import cn.cj.erp.common.http.Result;
import cn.cj.erp.common.security.security.asyncjob.AsyncFactory;
import cn.cj.erp.common.security.security.service.TokenService;
import cn.cj.erp.common.security.security.user.LoginUser;
import cn.cj.erp.common.threadpool.AsyncManager;
import cn.cj.erp.common.utils.ServletUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义退出处理类 返回成功
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Resource
    private TokenService tokenService;

    /**
     * 退出处理
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (loginUser != null) {
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser);
            AsyncManager.getInstance().execute(AsyncFactory.saveLoginLog(loginUser.getUsername(), StatusEnum.NORMAL, "退出成功"));
        }
        ServletUtils.renderStr(response, JSON.toJSONString(Result.ok("退出成功")));
    }
}
